<?php
namespace app\common\service;

use app\common\model\Admin;
use app\common\model\AuthRule;
use app\common\model\AuthGroup;
use app\common\model\AuthGroupAccess;

class Auth
{
    /**
     * 检查权限
     * @param int $admin_id 管理员id
     * @param string $auth 权限规则
     * @return bool
     */
    public function check($admin_id, $auth)
    {
        // 获取管理员所属用户组
        $groups = AuthGroupAccess::where('admin_id', $admin_id)
            ->column('group_id');
            
        if (!$groups) {
            return false;
        }

        // 获取用户组拥有的权限规则
        $rules = AuthGroup::where('id', 'in', $groups)
            ->where('status', 1)
            ->column('rules');
            
        $rules = array_unique(explode(',', implode(',', $rules)));

        // 检查权限
        return AuthRule::where('name', $auth)
            ->where('id', 'in', $rules)
            ->where('status', 1)
            ->count() > 0;
    }

    /**
     * 获取管理员权限列表
     * @param int $admin_id 管理员id
     * @return array
     */
    public function getAuthList($admin_id)
    {
        // 获取管理员所属用户组
        $groups = AuthGroupAccess::where('admin_id', $admin_id)
            ->column('group_id');
            
        if (!$groups) {
            return [];
        }

        // 获取用户组拥有的权限规则
        $rules = AuthGroup::where('id', 'in', $groups)
            ->where('status', 1)
            ->column('rules');
            
        $rules = array_unique(explode(',', implode(',', $rules)));

        // 获取权限列表
        return AuthRule::where('id', 'in', $rules)
            ->where('status', 1)
            ->select();
    }
} 